package com.ebeitech.doorapp.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.application.EbeiApplication;
import com.ebeitech.doorapp.domain.EMessage;
import com.ebeitech.doorapp.domain.dao.EMessageDao;
import com.ebeitech.doorapp.util.image.GlideCircleTransform;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.ui.badgeview.Badge;
import com.ebeitech.library.ui.badgeview.QBadgeView;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by alice on 2018/6/11.
 */

public class ChatActivity extends BaseActivity {

	@BindView(R.id.view_title)
	CommonTitleBar mTitleBarView;
	@BindView(R.id.listView)
	ListView mListView;

	private Context mContext;
	private BaseAdapter mAdapter;
	private List<EMessage> messageList = new ArrayList<EMessage>();
	private EMessageDao mMessageDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Intent intent = getIntent();
		if (savedInstanceState == null) {
			savedInstanceState = new Bundle();
		}
		if (intent != null) {
			savedInstanceState.putBoolean(SPConstants.IS_FIT_STATUS_BAR, intent.getBooleanExtra(SPConstants.IS_FIT_STATUS_BAR, true));
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_listview);
		ButterKnife.bind(this);
		mContext = this;
		mMessageDao = EMessageDao.getInstance();
		initView();
		registerBroadCast();
		loadMessage();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	private void initView() {
		mTitleBarView.setTitle(getString(R.string.ebei_message));
		mTitleBarView.setBtnBackVisible(false);

		mAdapter = new MessageAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setBackgroundResource(R.color.ebei_white);
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(action)) {
				EMessage message = (EMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
				message.setCount(1);
				if (message != null) {
					int index = -1;
					for (int i = 0; i < messageList.size(); i++) {
						EMessage messageT = messageList.get(i);
						if (message.getTypeId().equals(messageT.getTypeId())) {
							index = i;
							message.setCount(messageT.getCount() + 1);
							break;
						}
					}
					if (index > -1) {
						messageList.set(index, message);
					} else {
						messageList.add(0, message);
					}
					mAdapter.notifyDataSetChanged();
				}
			}
		}
	};

	private void loadMessage() {
		final CommonAlertDialogFragment mProgressDialog = ViewUtil.showProgressDialog(mContext);
		new AsyncTask<Void, Void, Void>() {

			private List<EMessage> messageListT = new ArrayList<EMessage>();
			private Map<String, Integer> messageUnreadMapT = new HashMap<String, Integer>();

			@Override
			protected Void doInBackground(Void... voids) {
				messageListT = mMessageDao.getMessageList();
				Cursor cursor = mMessageDao.queryCursor(new String[]{ "typeId", "count(*)" }, "readFlag = '" + EMessage.READ_FLAG_UNREAD + "' group by fromId", null);
				if (cursor != null) {
					cursor.moveToPosition(-1);
					while (cursor.moveToNext()) {
						String typeId = cursor.getString(0);
						int count = cursor.getInt(1);
						messageUnreadMapT.put(typeId, count);
					}
				}
				for (int i = 0; i < messageListT.size(); i++) {
					EMessage message = messageListT.get(i);
					if (messageUnreadMapT.containsKey(message.getTypeId())) {
						message.setCount(messageUnreadMapT.get(message.getTypeId()));
					}
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				super.onPostExecute(aVoid);
				messageList.clear();
				messageList.addAll(messageListT);
				if (!isFinishing()) {
					ViewUtil.dismissDialog(mProgressDialog);
				}
				messageList.clear();
				if (messageListT != null && messageListT.size() > 0) {
					messageList.addAll(messageListT);
				}
				mAdapter.notifyDataSetChanged();
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 1) {
				loadMessage();
			}
		}
	}

	class MessageAdapter extends BaseAdapter {

		private float imageWidth;
		private float maxWidth;
		private float imageMargin;

		public MessageAdapter() {
			imageWidth = ViewUtil.dp2px(mContext, 55);
		}

		@Override
		public int getCount() {
			return messageList.size();
		}

		@Override
		public Object getItem(int position) {
			return messageList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder mViewHolder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_chat_item, null);
				mViewHolder = new ViewHolder();
				mViewHolder.viewImage = convertView.findViewById(R.id.viewImage);
				mViewHolder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
				mViewHolder.badgeView = new QBadgeView(mContext);
				mViewHolder.badge = mViewHolder.badgeView.bindTarget(mViewHolder.ivImage).setGravityOffset(0, 0, false);
				mViewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
				mViewHolder.tvMsg = (TextView) convertView.findViewById(R.id.tvMsg);
				mViewHolder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
				convertView.setTag(mViewHolder);
			} else {
				mViewHolder = (ViewHolder) convertView.getTag();
			}

			EMessage message = (EMessage) getItem(position);
			String url = message.getFromLogo();
			if (EMessage.MESSAGE_TYPE_SYSTEM.equals(message.getMessageType())) {
				Glide.with(mContext).load(R.mipmap.ebei_ic_launcher).transform(new GlideCircleTransform(mContext)).into(mViewHolder.ivImage);
			} else {
				Glide.with(mContext).load(url).transform(new GlideCircleTransform(mContext)).into(mViewHolder.ivImage);
			}
			String time = message.getTime();
			if (!StringUtil.isStringNullOrEmpty(time)) {
				time = com.ebeitech.doorapp.qqim.util.TimeUtil.getChatTimeShortStrWithTimeMillis(TimeUtil.getTimeMillis(time));
			} else {
				time = "";
			}
			mViewHolder.tvTime.setText(time);
			mViewHolder.tvName.setText(message.getFromName());
			mViewHolder.tvMsg.setText(message.getContent());

			if (maxWidth == 0) {
				mViewHolder.badge.setBadgeNumber(100);
				maxWidth = mViewHolder.badgeView.getBadgeViewWidth();
				imageMargin = mViewHolder.badgeView.getBadgeViewHeight() / 2;
			}
			ViewGroup.LayoutParams lpImage= (ViewGroup.LayoutParams) mViewHolder.viewImage.getLayoutParams();
			int widthI = (int) (imageWidth + (maxWidth - ViewUtil.dp2px(mContext, 10)));
			lpImage.width = widthI;
			mViewHolder.viewImage.setLayoutParams(lpImage);

			int count = message.getCount();
			boolean isShowMsg = count > 0;
			Badge badge = mViewHolder.badge.setBadgeNumber(count);
			if (badge != null) {
				badge.setOnDragStateChangedListener(isShowMsg ?
						new Badge.OnDragStateChangedListener() {
							@Override
							public void onDragStateChanged(int dragState, Badge badge, View targetView) {
								if (dragState == STATE_SUCCEED) {
									// 置为已读
									mMessageDao.setMessageReadByType(message.getTypeId());
									message.setCount(0);
									mAdapter.notifyDataSetChanged();
								}
							}
						} : null);
			}

			mViewHolder.ivImage.setPadding(0, (int) imageMargin, 0, 0);
			ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) mViewHolder.ivImage.getLayoutParams();
			int width = (int) (imageWidth + (mViewHolder.badgeView.getBadgeViewWidth() - ViewUtil.dp2px(mContext, 10)));
			lp.width = width;
			mViewHolder.ivImage.setLayoutParams(lp);

			convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(mContext, MessageActivity.class);
					intent.putExtra(MessageConstants.MESSAGE_TYPE_ID, message.getTypeId());
					startActivityForResult(intent, 1);
				}
			});
			return convertView;
		}

		class ViewHolder {
			ViewGroup viewImage;
			ImageView ivImage;
			QBadgeView badgeView;
			Badge badge;
			TextView tvName;
			TextView tvMsg;
			TextView tvTime;
		}
	}

}
